package com.example.demotest.repository;

import com.example.demotest.pojo.Order;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface OrderRepository extends JpaRepository<Order, Integer> {

    // ================== 基础查询方法 ==================
    Optional<Order> findByOrderIdAndBuyerId(Integer orderId, Integer buyerId);

    List<Order> findByBuyerId(Integer buyerId);

    List<Order> findBySellerId(Integer sellerId);

    // 修正：orderStatus 是 Integer 类型，参数改为 Integer
    List<Order> findByOrderStatus(Integer status);


    // ================== 复杂查询方法 ==================
    @Query("SELECT o FROM Order o WHERE o.buyerId = :userId AND o.createdAt BETWEEN :start AND :end")
    List<Order> findUserOrdersBetweenDates(
            @Param("userId") Integer userId,
            @Param("start") LocalDateTime start,
            @Param("end") LocalDateTime end
    );


    // ================== 更新操作方法 ==================
    // 修正：status 改为 Integer 类型（与实体 orderStatus 一致）
    @Modifying
    @Query("UPDATE Order o SET o.orderStatus = :status, o.updatedAt = :now WHERE o.orderId = :orderId")
    int updateOrderStatus(
            @Param("orderId") Integer orderId,
            @Param("status") Integer status,  // 改为 Integer
            @Param("now") LocalDateTime now
    );

    // 修正：订单状态改为 Integer（如 1 表示已支付）
    @Modifying
    @Query("UPDATE Order o SET o.paymentMethod = :method, o.transactionId = :txId, " +
            "o.orderStatus = 1, o.updatedAt = :now WHERE o.orderId = :orderId")  // 直接使用状态码 1
    int markOrderAsPaid(
            @Param("orderId") Integer orderId,
            @Param("method") String paymentMethod,
            @Param("txId") String transactionId,
            @Param("now") LocalDateTime now
    );


    // ================== 统计方法 ==================
    // 修正：status 改为 Integer 类型
    @Query("SELECT COUNT(o) FROM Order o WHERE o.sellerId = :sellerId AND o.orderStatus = :status")
    long countBySellerAndStatus(
            @Param("sellerId") Integer sellerId,
            @Param("status") Integer status  // 改为 Integer
    );


    // ================== 存在性检查 ==================
    boolean existsByOrderIdAndBuyerId(Integer orderId, Integer buyerId);

    boolean existsByOrderIdAndSellerId(Integer orderId, Integer sellerId);

    List<Order> findByOrderStatusAndDeliveryStatus(Integer orderStatus, Order.DeliveryStatus deliveryStatus);
    List<Order> findByRiderId(Integer riderId);
}